package com.dyj.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.stream.Collectors;

public class FieldUtils {

    /**
     * 获取实体类的所有非静态字段名并用逗号连接
     *
     * @param clazz 实体类的Class对象
     * @return 逗号连接的非静态字段名字符串
     */
    public static String getFieldsString(Class<?> clazz) {
        return java.util.Arrays.stream(clazz.getDeclaredFields())
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .map(field -> camelToSnake(field.getName()))
                .collect(Collectors.joining(","));
    }

    /**
     * 驼峰转下划线
     */
    private static String camelToSnake(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                result.append('_').append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

}
